package site.lanmushan.quiz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.lanmushan.common.authorization.CurrentUserUtil;
import site.lanmushan.common.mapper.wrapper.DefaultWrapper;
import site.lanmushan.common.mapper.wrapper.QueryWrapper;
import site.lanmushan.common.query.service.BaseService;
import site.lanmushan.quiz.api.ao.SubmitAnswerAo;
import site.lanmushan.quiz.api.conts.QuestionTypeEnum;
import site.lanmushan.quiz.api.conts.QuizTbBankExamRecordStatusEnum;
import site.lanmushan.quiz.api.entity.QuizTbBankExamRecord;
import site.lanmushan.quiz.api.entity.QuizTbQuestion;
import site.lanmushan.quiz.api.entity.QuizTbQuestionAnswer;
import site.lanmushan.quiz.api.entity.QuizTbQuestionAnswerRecord;
import site.lanmushan.quiz.api.service.IQuizTbQuestionAnswerRecordService;
import site.lanmushan.quiz.api.vo.ExamQuestionListVo;
import site.lanmushan.quiz.api.vo.QuestionAnswersVo;
import site.lanmushan.quiz.mapper.QuizTbBankExamRecordMapper;
import site.lanmushan.quiz.mapper.QuizTbQuestionAnswerMapper;
import site.lanmushan.quiz.mapper.QuizTbQuestionAnswerRecordMapper;
import org.springframework.transaction.annotation.Transactional;
import site.lanmushan.quiz.mapper.QuizTbQuestionMapper;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author dy
 */

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class QuizTbQuestionAnswerRecordServiceImpl extends BaseService<QuizTbQuestionAnswerRecord, QuizTbQuestionAnswerRecordMapper> implements IQuizTbQuestionAnswerRecordService {
    @Autowired
    QuizTbQuestionAnswerRecordMapper quizTbQuestionAnswerRecordMapper;
    @Autowired
    QuizTbBankExamRecordMapper quizTbBankExamRecordMapper;
    @Autowired
    QuizTbQuestionMapper quizTbQuestionMapper;
    @Autowired
    QuizTbQuestionAnswerMapper quizTbQuestionAnswerMapper;

    @Override
    public List<ExamQuestionListVo> selectExamQuestionListByBankCodeAndExamId(String questionBankCode, Long examId) {
        return getQueryMapper().selectExamQuestionListByBankCodeAndExamId(questionBankCode, examId);
    }

    @Override
    public QuestionAnswersVo selectQuestionAndOptionsById(Long questionId, Long examId) {
        //查询题目
        QuizTbQuestion quizTbQuestion = quizTbQuestionMapper.selectByPrimaryKey(questionId);
        if (quizTbQuestion == null) {
            throw new IllegalArgumentException("题目不存在");
        }
        //查询答案选项
        QueryWrapper queryWrapper = new DefaultWrapper();
        queryWrapper.in("fk_question_id", questionId);
        List<QuizTbQuestionAnswer> list = quizTbQuestionAnswerMapper.selectAllList(queryWrapper);
        List<QuizTbQuestionAnswer> quizTbQuestionAnswers = list.stream().map(ite -> {
            ite.setScoreValue(null);
            ite.setAnswerCorrect(null);
            ite.setAnswerGroup(null);
            ite.setWeight(null);
            return ite;
        }).collect(Collectors.toList());
        QuestionAnswersVo questionAnswersVo = BeanUtil.copyProperties(quizTbQuestion, QuestionAnswersVo.class);
        questionAnswersVo.setAnswerList(quizTbQuestionAnswers);
        //查询答题记录
        QueryWrapper recordQueryWrapper = new DefaultWrapper();
        recordQueryWrapper.eq("fk_question_id", questionId);
        recordQueryWrapper.eq("exam_id", examId);
        List<QuizTbQuestionAnswerRecord> quizTbQuestionAnswerRecordList = getQueryMapper().selectAllList(recordQueryWrapper);
        if (!quizTbQuestionAnswerRecordList.isEmpty()) {
            questionAnswersVo.setAnswerRecord(quizTbQuestionAnswerRecordList.get(0));
        }
        return questionAnswersVo;
    }


    @Override
    public void doSubmitAnswer(SubmitAnswerAo entityAo) {
        QuizTbQuestion quizTbQuestion = quizTbQuestionMapper.selectByPrimaryKey(entityAo.getQuestionId());
        if (quizTbQuestion == null) {
            throw new IllegalArgumentException("题目不存在");
        }
        QuizTbBankExamRecord quizTbBankExamRecord = quizTbBankExamRecordMapper.selectByPrimaryKey(entityAo.getExamRecordId());
        if (quizTbBankExamRecord == null) {
            throw new IllegalArgumentException("考试记录不存在");
        }
        if (quizTbBankExamRecord.getStatus() != QuizTbBankExamRecordStatusEnum.ANSWERING.getStatus()) {
            throw new IllegalArgumentException("考试记录状态异常");
        }
        QuizTbQuestionAnswerRecord query = new QuizTbQuestionAnswerRecord();
        query.setFkQuestionId(entityAo.getQuestionId());
        query.setExamId(entityAo.getExamRecordId());
        query.setCreateUserAccount(CurrentUserUtil.getCurrentUser().getAccount());
        QuizTbQuestionAnswerRecord exits = quizTbQuestionAnswerRecordMapper.selectOne(query);
        if (exits != null) {
            quizTbQuestionAnswerRecordMapper.deleteByPrimaryKey(exits.getId());
        }
        QuestionTypeEnum questionTypeEnum = QuestionTypeEnum.valueOf(quizTbQuestion.getQuestionType());
        switch (questionTypeEnum) {
            case SingleChoice: {
                doSubmitAnswerSingleChoice(entityAo);
                break;
            }
            case MultipleChoice: {
                log.info("单选题提交");
                doSubmitAnswerMultipleChoice(entityAo);

                break;
            }
            case InputValue: {
                log.info("单选题提交");
                break;
            }
        }
    }

    private void doSubmitAnswerMultipleChoice(SubmitAnswerAo entityAo) {
        if (entityAo.getAnswerValues().size() < 1) {
            throw new IllegalArgumentException("多选题至少选择一个答案");
        }
        List<Long> answerIds = entityAo.getAnswerValues().stream().map(ite -> ite.getId()).collect(Collectors.toList());
        List<QuizTbQuestionAnswer> quizTbQuestionAnswers = quizTbQuestionAnswerMapper.selectByIdList(answerIds);
        if (quizTbQuestionAnswers.size() != entityAo.getAnswerValues().size()) {
            throw new IllegalArgumentException("答案不存在");
        }
        //组装答案记录
        QuizTbQuestionAnswerRecord quizTbQuestionAnswerRecord = new QuizTbQuestionAnswerRecord();
        quizTbQuestionAnswerRecord.setFkQuestionId(entityAo.getQuestionId());
        quizTbQuestionAnswerRecord.setAnswerContent(quizTbQuestionAnswers.stream().map(ite -> ite.getAnswerContent()).collect(Collectors.joining(",")));
        //judge是否有分值，有则使用，没有则使用题目的分数
        if (quizTbQuestionAnswers.stream().allMatch(ite -> ite.getAnswerCorrect() == 1 && ite.getScoreValue() != null)) {
            quizTbQuestionAnswerRecord.setAnswerScore(quizTbQuestionAnswers.stream().mapToDouble(ite -> ite.getScoreValue()).sum());
        }
        //插入记录
        quizTbQuestionAnswerRecord.setAnswerIds(String.join(",", answerIds.toArray(new String[0])));
        quizTbQuestionAnswerRecord.setIsCorrect(quizTbQuestionAnswers.stream().allMatch(ite -> ite.getAnswerCorrect() == 1) ? 1 : 0); //正确
        quizTbQuestionAnswerRecord.setAnswerDimension(quizTbQuestionAnswers.stream().map(ite -> ite.getAnswerGroup()).collect(Collectors.joining(",")));
        quizTbQuestionAnswerRecord.setWeight(quizTbQuestionAnswers.stream().mapToDouble(ite -> ite.getWeight()).sum());
        quizTbQuestionAnswerRecord.setExamId(entityAo.getExamRecordId());
        super.insertService(quizTbQuestionAnswerRecord);
    }

    public void doSubmitAnswerSingleChoice(SubmitAnswerAo entityAo) {
        if (entityAo.getAnswerValues().size() != 1) {
            throw new IllegalArgumentException("单选题只能有一个答案");
        }
        QuizTbQuestionAnswer quizTbQuestionAnswer = quizTbQuestionAnswerMapper.selectByPrimaryKey(entityAo.getAnswerValues().get(0).getId());
        if (quizTbQuestionAnswer == null) {
            throw new IllegalArgumentException("答案不存在");
        }
        //组装答案记录
        QuizTbQuestionAnswerRecord quizTbQuestionAnswerRecord = new QuizTbQuestionAnswerRecord();
        quizTbQuestionAnswerRecord.setFkQuestionId(entityAo.getQuestionId());
        quizTbQuestionAnswerRecord.setAnswerContent(quizTbQuestionAnswer.getAnswerContent());
        //judge是否有分值，有则使用，没有则使用题目的分数
        if (Integer.valueOf(quizTbQuestionAnswer.getAnswerCorrect()) == 1 && quizTbQuestionAnswer.getScoreValue() != null) {
            quizTbQuestionAnswerRecord.setAnswerScore(quizTbQuestionAnswer.getScoreValue());
        }
        //插入记录
        quizTbQuestionAnswerRecord.setAnswerIds(String.valueOf(quizTbQuestionAnswer.getId()));
        quizTbQuestionAnswerRecord.setIsCorrect(quizTbQuestionAnswer.getAnswerCorrect()); //正确
        quizTbQuestionAnswerRecord.setAnswerDimension(quizTbQuestionAnswer.getAnswerGroup());
        quizTbQuestionAnswerRecord.setWeight(quizTbQuestionAnswer.getWeight());
        quizTbQuestionAnswerRecord.setExamId(entityAo.getExamRecordId());
        super.insertService(quizTbQuestionAnswerRecord);

    }
}
